// audio-player.js
Component({
  properties: {
    audioUrl: {
      type: String,
      value: ''
    },
    audioTitle: {
      type: String,
      value: '未知音频'
    }
  },

  data: {
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    formattedCurrentTime: '00:00',
    formattedDuration: '00:00',
    audioContext: null
  },

  lifetimes: {
    attached() {
      this.initAudio();
    },
    detached() {
      this.destroyAudio();
    }
  },

  methods: {
    initAudio() {
      const audioContext = wx.createInnerAudioContext();
      audioContext.src = this.properties.audioUrl;

      // 播放状态监听
      audioContext.onPlay(() => {
        this.setData({ isPlaying: true });
      });

      audioContext.onPause(() => {
        this.setData({ isPlaying: false });
      });

      audioContext.onStop(() => {
        this.setData({ isPlaying: false });
      });

      // 时间更新监听
      audioContext.onTimeUpdate(() => {
        const currentTime = audioContext.currentTime;
        const duration = audioContext.duration || this.data.duration;
        this.setData({
          currentTime,
          duration,
          formattedCurrentTime: this.formatTime(currentTime),
          formattedDuration: this.formatTime(duration)
        });
      });

      // 元数据加载
      audioContext.onCanplay(() => {
        if (audioContext.duration > 0) {
          this.setData({
            duration: audioContext.duration,
            formattedDuration: this.formatTime(audioContext.duration)
          });
        }
      });

      // 错误处理
      audioContext.onError((err) => {
        console.error('音频播放错误:', err);
        wx.showToast({
          title: '音频加载失败',
          icon: 'none'
        });
      });

      this.setData({ audioContext });
    },

    destroyAudio() {
      if (this.data.audioContext) {
        this.data.audioContext.stop();
        this.data.audioContext.destroy();
        this.setData({ audioContext: null });
      }
    },

    togglePlay() {
      const { audioContext, isPlaying } = this.data;
      isPlaying ? audioContext.pause() : audioContext.play();
    },

    onSliderChange(e) {
      const { audioContext } = this.data;
      const value = e.detail.value;
      audioContext.seek(value);
      if (!this.data.isPlaying) {
        audioContext.play();
      }
    },

    onSliderChanging(e) {
      this.setData({
        currentTime: e.detail.value,
        formattedCurrentTime: this.formatTime(e.detail.value)
      });
    },

    formatTime(seconds) {
      if (isNaN(seconds)) return '00:00';
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
  }
});